Skip to content

应用lil-GUI调试开发3D效果

代码

js
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
// 导入 lil.gui
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js';

const scene = new THREE.Scene();


const camera = new THREE.PerspectiveCamera(
  45,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
)

const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)


const geometry = new THREE.BoxGeometry(1, 1, 1)

const material = new THREE.MeshBasicMaterial({
  color: 0x00ff00
})
const parentMaterial = new THREE.MeshBasicMaterial({
  color: 0xff0000
})
parentMaterial.wireframe = true;


let parentCube = new THREE.Mesh(geometry, parentMaterial)
const cube = new THREE.Mesh(geometry, material)
parentCube.add(cube)
parentCube.position.set(-3, 0, 0)
parentCube.rotation.x = Math.PI / 4;

cube.position.set(2, 2, 2)
cube.rotation.x = Math.PI / 4

scene.add(parentCube)

camera.position.z = 5;
camera.position.y = 2;
camera.position.x = 2;
camera.lookAt(0, 0, 0)

const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);

const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;

function animate() {
  requestAnimationFrame(animate)
  controls.update()

  renderer.render(scene, camera)
}

animate()

// 监听窗口变化
window.addEventListener('resize', () => {
  // 重置渲染器宽高比
  renderer.setSize(window.innerWidth, innerHeight)
  // 重置相机宽高比
  camera.aspect = window.innerWidth / window.innerHeight
  // 更新相机投影矩阵
  camera.updateProjectionMatrix()
})

let eventObj = {
  Fullscreen: function () {
    document.body.requestFullscreen()
  },
  ExitFullscreen: function () {
    document.exitFullscreen()
  }
}

// 创建GUI
const gui = new GUI()
// 添加按钮
gui.add(eventObj, 'Fullscreen').name('全屏')
gui.add(eventObj, 'ExitFullscreen').name('退出全屏')

// 控制立方体的位置
gui.add(cube.position, 'x', -5, 5).name('立方体x轴位置')
gui.add(cube.position, 'y').min(-10).max(10).step(1).name('立方体y轴位置')
gui.add(cube.position, 'z')
  .min(-10)
  .max(10)
  .step(1)
  .name('立方体z轴位置')
  .onFinishChange(val => console.log('立方体z轴位置:', val))

let folder = gui.addFolder('立方体的位置')
folder.add(cube.position, 'x', -5, 5).name('立方体x轴位置').onChange(val => {
  console.log('x轴位置:', val)
})

gui.add(parentMaterial, 'wireframe').name('父元素线框模式')
let colorParams = {
  cubeColor: '#00ff00',
}

gui.addColor(colorParams, 'cubeColor').name('立方体颜色').onChange(val => {
  cube.material.color.set(val)
})